package org.lzy.shop.util

import android.Manifest
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.database.Cursor
import android.net.Uri
import android.os.Build
import android.provider.MediaStore
import android.util.SparseArray
import android.util.SparseBooleanArray
import android.util.SparseIntArray
import android.util.SparseLongArray
import android.util.TypedValue
import androidx.collection.SimpleArrayMap
import kotlinx.coroutines.CoroutineExceptionHandler
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.launch
import org.lzy.shop.BaseApplication
import java.io.File
import java.io.FileOutputStream
import java.lang.reflect.Array
import java.text.SimpleDateFormat
import java.util.Date

object MyUtil {


    fun getDataTime(format: String): String {
        val df = SimpleDateFormat(format)
        return df.format(Date())
    }

    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    fun dip2px(context: Context, dpValue: Float): Int {
        val r = context.resources
        val px = TypedValue.applyDimension(
            TypedValue.COMPLEX_UNIT_DIP,
            dpValue, r.displayMetrics
        )
        return px.toInt()
    }

    /**
     * ********************************
     * 拨打电话号码
     * *********************************
     */
    fun cellPhone(context: Activity, phoneNum: String?) {
        try {
            val intent = Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + phoneNum))
            intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK

            if (context.checkSelfPermission(Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
                // 申请一个（或多个）权限，并提供用于回调返回的获取码（用户定义)
                context.requestPermissions(arrayOf<String?>(Manifest.permission.CALL_PHONE), 1)
                return
            }
            context.startActivity(intent)
        } catch (e: Exception) {
        }
    }

    /**
     * 将Uri转换为File对象
     */
     fun getFileFromUri(uri: Uri): File? {
        try {
            val inputStream = BaseApplication.getContext().contentResolver.openInputStream(uri)
            if (inputStream == null) {
                return null
            }

            // 获取文件名
            val fileName = getFileNameFromUri(uri) ?: "temp_image.jpg"

            // 创建临时文件
            val file = File(BaseApplication.getContext().cacheDir, fileName)
            val outputStream = FileOutputStream(file)

            // 复制文件内容
            val buffer = ByteArray(4 * 1024)
            var bytesRead: Int
            while (inputStream.read(buffer).also { bytesRead = it } != -1) {
                outputStream.write(buffer, 0, bytesRead)
            }

            outputStream.flush()
            outputStream.close()
            inputStream.close()

            return file
        } catch (e: Exception) {
            e.printStackTrace()
            return null
        }
    }

    /**
     * 从Uri获取文件名
     */
    private fun getFileNameFromUri(uri: Uri): String? {
        var fileName: String? = null

        // 尝试从MediaStore获取文件名
        val projection = arrayOf(MediaStore.Images.Media.DISPLAY_NAME)
        val cursor: Cursor? = BaseApplication.getContext().contentResolver.query(uri, projection, null, null, null)

        cursor?.use {
            if (it.moveToFirst()) {
                val nameColumnIndex = it.getColumnIndexOrThrow(MediaStore.Images.Media.DISPLAY_NAME)
                fileName = it.getString(nameColumnIndex)
            }
        }

        // 如果MediaStore查询失败，尝试从Uri路径提取
        if (fileName == null) {
            fileName = uri.lastPathSegment
        }

        return fileName
    }
}